<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Home/
class Controller_Post extends Controller_Base 
{
	private $postService;
	private $commentService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		$this->postService = new Service_PostServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_POST.'/', ACCESS_TOKEN);
		$this->postService->init($this->_requestContext);

		$this->commentService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_COMMENT.'/', ACCESS_TOKEN);
		$this->commentService->init($this->_requestContext);
	}
	
	public function action_show_list()
	{	
		$content = View::factory($this->_theme.'/home' );
		try {
			$content->posts = $this->postService->getList(array(), 0, 10);
			
			$this->template->content = $content;
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Lis | Message: ' . $ex->getMessage());
		}
	
	}
	
	public function action_add()
	{
		if (!$post = $_POST) return;
		$body = $this->request->post('postBody');
		$projectSid = $this->request->post('projectSid');
		
		$tagsCsv = $post['tagsCsv'];
		$sid = $this->postService->addPost($projectSid, $body, $tagsCsv);
		
		$redirTo = CONTROLLERPAGE.'/Home';
		$this->request->redirect($redirTo);
	}
	
	public function action_addcomment()
	{
		if (!$post = $_POST) return;
		
		$params = array('targetType'=>'Post');
		$params['targetSid'] = (int)$this->request->post('targetSid');
		$params['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
		$params['body'] = $this->request->post('body');
		$sid = $this->commentService->add($params);
		
		$redirTo = CONTROLLERPAGE.'/Home';
		$this->request->redirect($redirTo);
	}
	
	public function action_json_add()
	{
		if (!$post = $_POST) return;
		
		$this->_isRpc = true;
		$this->template = View::factory('rpc/json' );
		
		$retval = array('status'=>'ok');
		try {
			$body = $post['postBody'];

			$sid = $this->postService->add($body, null);
			if (!is_null($sid)) {
				$retval['sid'] = $sid;
				$retval['body']= $body;
			} else {
				$retval['status'] = 'error';
				$retval['error_message'] =  "PostService::add did not return valid value.";
			}
//Debug::vars($sid);
		} catch (Exception $ex)
		{
			$retval['status'] = 'error';
			$retval['error_message'] =  $ex->getMessage();
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add Post | Message: ' . $ex->getMessage());
		}
  		
		$this->template->content = json_encode($retval);
	}
	
	
} // End Controller_Home